package cn.pubinfo.shiro;

import cn.pubinfo.model.RolePermission;
import cn.pubinfo.model.User;
import cn.pubinfo.service.RolePermissionService;
import cn.pubinfo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * Created by zck on 2017/8/4.
 */
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private RolePermissionService rolePermissionService;

    //添加角色
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getRole().trim());
        List<RolePermission> rolePermissions = rolePermissionService.listByRole(user.getRole().trim());
        for (RolePermission rolePermission:rolePermissions){
            info.addStringPermission(rolePermission.getPermission());
        }
        return info;
    }

    //登陆认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.getByUsername(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException();
        }
        Object principal = user.getUsername();
        Object credentials = user.getPassword();
        ByteSource salt = null;
        if (user.getSalt() != null) {
            salt = ByteSource.Util.bytes(user.getSalt());
        }
        String realmName = getName();
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
        return new SimpleAuthenticationInfo(principal, credentials, salt, realmName);
    }
}
